package com.swingolf.dao.hrd;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.swingolf.dao.GuiStatusDAO;
import com.swingolf.model.Tournament;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * The <code>HRDTemperatureDAOImpl</code> provides crud methods for accessing collecting temperatures.
 */
@Repository
public class HRDGuiStatusDAOImpl implements GuiStatusDAO {

  @Override
  public void save(String key, String value) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity temperatureEntity = new Entity("GuiStatus");
    if (find(key) != null) {
      Query q = new Query("GuiStatus");
      q.addSort("key", Query.SortDirection.ASCENDING);
      PreparedQuery pq = datastore.prepare(q);
      List<Tournament> result = new LinkedList<Tournament>();
      Iterable<Entity> iterable = pq.asIterable();
      for (Entity entity : iterable) {
        if (entity.getProperty("key").equals(key)) {
          temperatureEntity = entity;
        }
      }
    }
    temperatureEntity.setProperty("key", key);
    temperatureEntity.setProperty("value", value);
    Key dsKey = datastore.put(temperatureEntity);
  }

  @Override
  public String find(String key) {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query q = new Query("GuiStatus");
    q.addSort("key", Query.SortDirection.ASCENDING);
    PreparedQuery pq = datastore.prepare(q);
    List<Tournament> result = new LinkedList<Tournament>();
    Iterable<Entity> iterable = pq.asIterable();
    //for (Entity entity : iterable) {
    //  datastore.delete(entity.getKey());
    //}
    for (Entity entity : iterable) {
      if (entity.getProperty("key").equals(key)) {
        return (String) entity.getProperty("value");
      }
    }
    return null;

  }
}
